package cn.chencq.moudle.thuser.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import cn.chencq.exception.MyException;
import cn.chencq.moudle.sys.dao.BaseDao;
import cn.chencq.moudle.sys.service.impl.BaseServiceImpl;
import cn.chencq.moudle.thuser.dao.ThUserDao;
import cn.chencq.moudle.thuser.entity.ThUser;
import cn.chencq.moudle.thuser.service.ThUserService;
import cn.chencq.utils.DateUtils;
import cn.chencq.utils.ThRequestUtils;
import cn.chencq.utils.redis.RedisUtils;

@Service
public class ThUserServiceImpl extends BaseServiceImpl<ThUser> implements ThUserService {

	private static final Logger logger = LoggerFactory.getLogger("thUserLogger");

	private static final String LOGIN_PASSWD = "login:password";
	private static final String WITHDRAW_PASSWD = "withdraw:password";

	@Autowired
	private ThUserDao thUserDao;

	@Autowired
	private RedisUtils redis;

	@Override
	protected BaseDao getBaseDao() {
		return this.thUserDao;
	}

	@Override
	public void saveOrUpdate(ThUser user) {
		thUserDao.saveOrUpdate(user);
	}

	@Override
	public List<ThUser> checkLoginPassword(String name, String password, String type) {
		List<ThUser> resList = new ArrayList<ThUser>();

		long l = redis.sadd(LOGIN_PASSWD, password);

		if (l == 0L) { // 表示密码已经校验
			throw new MyException("该登录密码已经校验过。");
		}

		List<ThUser> userList = new ArrayList<>();
		if (StringUtils.isNotBlank(name)) {
			ThUser u = thUserDao.queryByName(name);
			userList.add(u);
		}else {
			Map<String, Object> params = new HashMap<String, Object>();
			if(StringUtils.isNotBlank(type)){
				params.put("type", type);
			}
			userList = thUserDao.queryList(params);
		}

		String opt = "2"; // 登录接口
		JSONObject auth = new JSONObject();
		auth.put("loginType", "1");
		auth.put("imei", System.currentTimeMillis());
		auth.put("time_stamp", DateUtils.date2Str(new Date(), "yyyyMMddhhmmsssss"));
		auth.put("os", "Android");
		auth.put("os_version", "5.0");
		auth.put("app_version", "1.2.8");
		auth.put("source_id", "Yek_test");
		auth.put("ver", "0.9");
		auth.put("app_key", "123456");

		JSONObject info = new JSONObject();

		for (ThUser user : userList) {
			if(StringUtils.isNotBlank(user.getLoginPassword())) {
				continue;
			}
			
			if (StringUtils.isBlank(password)) {
				password = user.getName();
			}
			info.put("password", ThRequestUtils.md5(password + ThRequestUtils.KEY));

			auth.put("UID", user.getUid());
			info.put("name", user.getName());
			try {
				String res = ThRequestUtils.thRequest(opt, auth.toString(), info.toString());
				JSONObject json = JSONObject.parseObject(res);
				if (null != json && "0".equals(json.getString("error"))) {
					logger.info("密码验证通过, password:{}, userName:{}", password, user.getName());
					user.setLoginPassword(password);
					thUserDao.updatePassword(user);
					resList.add(user);
				}
			} catch (IOException e) {
				logger.error("请求登录接口异常", e);
			}
		}

		return resList;
	}

	@Override
	public List<ThUser> checkWithdrawPassword(String password, String type) {
		List<ThUser> resList = new ArrayList<ThUser>();

		long l = redis.sadd(WITHDRAW_PASSWD, password);

		if (l == 0L) { // 表示密码已经校验
			throw new MyException("提现密码已经校验过。");
		}
		String oldPassword = "135789";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", type);
		List<ThUser> userList = thUserDao.queryList(params);
		for (ThUser user : userList) {
			if(StringUtils.isNotBlank(user.getWithdrawPassword())) {
				continue;
			}
			String uid = user.getUid();
			if (StringUtils.isBlank(password)) {
				password = user.getName();
			}
			
			if(modifyWithdrawPassword(uid, oldPassword, password)) {
				logger.info("提现密码修改通过,password:{}, userName:{}, uid:{}", password, user.getName(), user.getUid());
				user.setWithdrawPassword(password);
				thUserDao.updatePassword(user);
				modifyWithdrawPassword(uid, password, oldPassword);
				resList.add(user);
			}
		}
		return resList;
	}

	/**
	 * 
	 * @Title: modifyWithdrawPassword
	 * @Description: 提现密码修改
	 * @param uid
	 * @param oldPassword
	 * @param newPassword
	 * @return boolean true 修改成功
	 */
	private boolean modifyWithdrawPassword(String uid, String oldPassword, String newPassword) {
		boolean flag = false;
		String opt = "59"; // 提现密码修改接口
		JSONObject auth = new JSONObject();
		auth.put("loginType", "1");
		auth.put("imei", System.currentTimeMillis());
		auth.put("time_stamp", DateUtils.date2Str(new Date(), "yyyyMMddhhmmsssss"));
		auth.put("os", "Android");
		auth.put("os_version", "5.0");
		auth.put("app_version", "1.2.8");
		auth.put("source_id", "Yek_test");
		auth.put("ver", "0.9");
		auth.put("app_key", "123456");
		auth.put("UID", uid);
		JSONObject info = new JSONObject();
		info.put("theNewPassword", ThRequestUtils.md5(newPassword + ThRequestUtils.KEY));
		info.put("password", ThRequestUtils.md5(oldPassword + ThRequestUtils.KEY));
		try {
			String res = ThRequestUtils.thRequest(opt, auth.toString(), info.toString());
			JSONObject json = JSONObject.parseObject(res);
			if (null != json && "0".equals(json.getString("error"))) {
				flag = true;
			}
		} catch (IOException e) {
			logger.error("请求提现密码修改异常", e);
		}
		return flag;
	}
}
